package sk.naive.talker.tcpadapter;

import sk.naive.talker.adapter.*;

import java.util.*;

/**
 * ColsTagProcessor layouts items into columns.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.3 $ $Date: 2004/11/14 17:39:12 $
 */
public class ColsTagProcessor implements TagProcessor {
	public String process(MessageProcessingContext ctx, String params) throws TagProcessorException {
		Collection<String> items = ((ItemTagProcessor.ItemConsumer) ctx.getConsumer()).items();
		int maxLen = 0;
		for (String item : items) {
			if (item.length() > maxLen) {
				maxLen = item.length();
			}
		}
		int colWidth = maxLen + 1;
		int cols = ((TCPUser) ctx.getUser()).getCols() / colWidth;
		if (params != null) {
			cols = Integer.parseInt(params);
		}
		int rows = (items.size() - 1) / cols + 1;
		StringBuilder buffer = new StringBuilder(ctx.getConsumer().result());
		for (int i = 0; i < rows; i++) {
			Iterator it = items.iterator();
			for (int j = 0; j < i; j++) {
				it.next();
			}
			while (it.hasNext()) {
				String item = (String) it.next();
				buffer.append(((TCPUser) ctx.getUser()).ansiReset()).append(item);
				for (int j = item.length(); j < colWidth; j++) {
					buffer.append(' ');
				}
				for (int j = 1; j < rows; j++) {
					if (!it.hasNext()) {
						break;
					}
					it.next();
				}
			}
			buffer.append(((TCPUser) ctx.getUser()).ansiReset()).append(TCPUser.TCP_BR);
		}
		ctx.switchConsumer(new MessageProcessingContext.BufferMessageConsumer(), false);
		return buffer.toString();
	}
}

